package com.example.springbolgdemo.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {

    //通过算法生成一个key
    //private static final SecretKey KEY= Keys.secretKeyFor(SignatureAlgorithm.ES256);
    private static final String KEYSTRING="ZGyMxy1sKDajurjL9vZhsTtM0QzD_3so_5ONs9LGQDY";
    private static final SecretKey KEY=Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(KEYSTRING));
    private static final long EXPIRE_TIME=7*24*60*60*1000;

    public static String genToken(Map<String,Object> claim){
        String token= Jwts.builder()
                .setClaims(claim)//设置载荷Payload
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))//设置过期时间
                .signWith(KEY)//设置签名
                .compact();//生成token
        return token;
    }

    public static Claims parseToken(String token){
        JwtParser bulid=Jwts.parserBuilder().setSigningKey(KEY).build();//创建token解析器
        Claims body=null;
        try {
            body=bulid.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("token解析失败,token:",token);
        }
        return body;
    }


}
